package org.opengoss.db.hsqldb;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

/**
 * TODO: Confused that the server could not be started in the main thread, it 
 * almost spend 5 minutes to start the server and then block the main thread.  
 * 
 * @author Ery Lee(ery.lee@gmail.com)
 * @since 1.0 20061228
 */
public class HsqlDBActivator implements BundleActivator {
	
	private Server server;
	
	private Thread daemon;
	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		server = new Server();
		//init server properties
		InputStream is1 = null; 
		InputStream is2 = null;
		try {
			String etcPath = "./etc/" + context.getBundle().getSymbolicName();
			is1 = new FileInputStream(etcPath + "/server.properties");
			Properties svProps = new Properties();
			svProps.load(is1);
			server.setProperties(new HsqlProperties(svProps));
			
			is2 = new FileInputStream(etcPath + "/database.properties");
			Properties dbProps = new Properties();
			dbProps.load(is2);
			for (Iterator it = dbProps.keySet().iterator(); it.hasNext();) {
				String key = (String) it.next();
				if(key.startsWith("database.")) {
					server.setDatabasePath(getIndex(key), dbProps.getProperty(key));
				} else if(key.startsWith("dbname.")) {
					server.setDatabaseName(getIndex(key), dbProps.getProperty(key));
				}
			}
		} finally {
			if(is1 != null) {
				is1.close();
			}
			if(is2 != null) {
				is2.close();
			}
		}
		daemon = new Thread(new Runnable() {
			public void run() {
				server.start();		
			}
		});
		daemon.start();
		Thread.sleep(3000);
	}

	private int getIndex(String key) {
		return Integer.parseInt( key.substring(key.indexOf('.') + 1) );
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		if(server != null) {
			server.shutdown();
		}
		if(daemon != null) {
			daemon.join(1000);
			daemon.interrupt();
		}
		daemon = null;
		server = null;
	}

}
